<template>
  <div
    ref="buttonRef"
    class="back-to-top"
    @click="scrollToTop"
    v-show="isVisible"
  >
    <i class="icon-top iconfont" />
</div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';

const buttonRef = ref<HTMLElement | null>(null);
const parentContainer = ref<HTMLElement | null>(null);
const isVisible = ref(false);

onMounted(() => {
  if (buttonRef.value) {
    parentContainer.value = buttonRef.value.parentElement;
    if (parentContainer.value) {
      parentContainer.value.addEventListener('scroll', handleScroll);
      parentContainer.value.addEventListener('resize', handleScroll);
      handleScroll();
    }
  }
});

const handleScroll = () => {
  if (parentContainer.value) {
    const scrollY = parentContainer.value.scrollTop;
    isVisible.value = scrollY > 100;
  }
};

const scrollToTop = () => {
  if (parentContainer.value) {
    parentContainer.value.scrollTop = 0;
  }
};
</script>

<style>
.back-to-top {
  position: fixed;
  bottom: 60px;
  right: 20px;
  z-index: 999;
  border-radius: 50%;
  cursor: pointer;
  font-size: 18px;
  transition: all 0.3s ease;
  height: 36px;
  width: 36px;
  background: #eee;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* .back-to-top.visible {
  opacity: 1;
  transform: translateY(0);
} */

.back-to-top:hover {
  background-color: #999;
}
</style>